<template>
  <div>
    <div class="chat_msg_con">
      <el-row>
        <el-col :span="24">
          <div class="chatMsgCon">
            <div class="chat_msg" :class="chatMsgClass" :style="chat_msg_ai_height" v-on:scroll="getChatHistoryScroll($event)">
              <div class="msg_inner" :class="chatInfo.showHistoryBtn ? '' : 'height_limit'">
                <div class="wxend" v-show="chatInfo.showHistoryBtn && loadFlag">
                  <a href="javascript:;" @click.stop="queryMessageHistory">{{$t('webchat.viewHistorySession')}}</a>
                </div>
                <div class="history_liading" v-show="loadFlag === false">
                  <div class="history_liading_text">
                    <img src="./img/loading.gif" alt=""><span>{{$t('webchat.loading')}}</span>
                  </div>
                </div>
                <div class="chatUserMsg">
                  <!-- 会话展示重构 070919 by liujing -->
                  <div v-for="(chatMsg, index) in messageList"
                       class="msg_li clearBoth"
                       :class="msgClass(chatMsg)"
                       v-if="chatMsg.contentType !== 'csr'">
                    <!-- 系统消息 -->
                    <div class="chat_item system clearBoth" v-if="(chatMsg.type === 'system' || chatMsg.type === 'imcsr' || chatMsg.type === 'sessionFormSubmit')">
                      <div class="chat_content" v-if="chatMsg.type === 'system' && chatMsg.msgType !== 'saveImCSRInfo' && chatMsg.contentType !== 'sessionFormSubmit' && chatMsg.msgType !== 'withdrawMessage'">
                        {{(chatMsg.dateTime ? chatMsg.dateTime : '')  + ' ' + chatMsg.message}}
                      </div>
                      <div class="chat_content" v-if="chatMsg.msgType === 'withdrawMessage'">
                        {{(chatMsg.dateTime ? chatMsg.dateTime : '')  + ' ' + chatMsg.message}}
                        <el-button class="withdrawReedit" type="text" @click="withdrawReedit(chatMsg)">{{$t('webchat.re-edit')}}</el-button>
                      </div>
                      <div class="chat_content" v-if="chatMsg.type === 'imcsr' || (chatMsg.type === 'system' && chatMsg.msgType === 'saveImCSRInfo')">
                        <span>{{chatMsg.dateTime ? chatMsg.dateTime : ''}}</span>
                        <span class="imcsrRed" v-if="CSRShowToAgent === 'part' && !satisfactioEvaluation">{{' ' + $t('webchat.userEvaluated')}}</span>
                        <span v-if="CSRShowToAgent === 'all' || satisfactioEvaluation" class="imcsrRed">{{' ' + chatMsg.message}}</span>
                      </div>
                      <!-- 访客端表单消息提交成功,座席端展示 -->
                      <div class="chat_item system clearBoth" v-if="chatMsg.contentType === 'sessionFormSubmit'">
                        <div class="chat_content">
                          {{(chatMsg.dateTime ? chatMsg.dateTime : '')  + ' ' + $t('webchat.submitFormMsg', {message: chatMsg.message})}} 
                          <el-popover
                            placement="right"
                            width="300"
                            trigger="hover">
                            <div class="formMsgLi" v-for="(data, i) in chatMsg.sessionFormSubmit">
                              <span class="formMsgLiAttr">{{i}}</span>:<span class="formMsgLiData" :title="data">{{data}}</span>
                            </div>
                            <el-button class="checkSessionForm" type="text" slot="reference">{{$t('webchat.view')}}</el-button>
                          </el-popover>
                        </div>
                      </div>
                    </div>
                    <!-- 非系统消息 -->
                    <div v-else class="chat_item clearBoth" :style="{maxWidth: chatMsg.contentType === 'newCardInfo' && expandLayout ? '' : '70%'}" :class="chatMsg.type === 'out' ? 'out chat_msg_con_item' : 'in'" @mouseenter="disabledFun(chatMsg)">
                      <!-- 微信小程序消息发送失败 -->
                      <el-tooltip v-if="chatMsg.type === 'out' && (chatMsg.wxminires || chatMsg.weixinres || chatMsg.sendRes) && (chatMsg.platform === 'wxmini' || chatMsg.platform === 'weixin' || chatMsg.platform === 'dy' || chatMsg.platform === 'wxkf')" :content="errorCodeFun(chatMsg)" placement="left">
                        <div v-if="chatMsg.type === 'out' && (chatMsg.wxminires || chatMsg.weixinres || chatMsg.sendRes) && (chatMsg.platform === 'wxmini' || chatMsg.platform === 'weixin' || chatMsg.platform === 'dy' || chatMsg.platform === 'wxkf')" class="send_status failure iconfont icon-tishi"></div>
                      </el-tooltip>
                      <!-- 消息发送状态框 -->
                      <div v-show="chatMsg.type === 'out' && isShowDealMsgStatus && (chatMsg.platform === 'wap' || chatMsg.platform === 'pc' || (chatMsg.platform === 'sdk' && sdkVcode))" :style="{color: chatMsg.dealUserMsg === true ? '#cbcbcb' : '#459ae9'}" class="chat_dealMsg_status">
                        {{chatMsg.dealMsgStatus}}
                      </div>
                      <div class="chat_send_status" v-if="userId === chatMsg.user" v-show="(!(chatMsg.type === 'out' && (chatMsg.wxminires || chatMsg.weixinres || chatMsg.sendRes) && (chatMsg.platform === 'wxmini' || chatMsg.platform === 'weixin' || chatMsg.platform === 'dy' || chatMsg.platform === 'wxkf')) && chatMsg.timeStamp)" :class="chatMsg.sendStatus && chatMsg.sendStatus !== 'sending' ? chatMsg.sendStatus === 'success' ? 'success' : 'fail' : ''">
                        <span class="shield_chat_arrow"></span>
                      </div>
                      <!-- 消息撤回框 -->
                      <div v-show="chatMsg.tipDisabled" class="shield_chat_box">
                        <span class="shield_chat" @click="shieldClick(chatMsg, $event, index)">{{$t('webchat.withdraw')}}</span>
                        <span class="shield_chat_arrow"></span>
                      </div>
                      <!-- 纯文本 -->
                      <div v-if="chatMsg.contentType === 'text'" class="chat_content" :style="(chatMsg.isExistFocusWords && chatMsg.type === 'in')?'background-color:#'+ chatMsg.backgroundColor:''" :class="chatMsg.type === 'in' && tabType === 'webchat_todo' ? 'do_search' : ''">
                        <div :class="chatMsg.type === 'out' ? 'chat_content_arrow_out' : 'chat_content_arrow'" :style="(chatMsg.isExistFocusWords&&chatMsg.type === 'in')?'border: 5px solid #'+ chatMsg.backgroundColor+';border-color: #'+chatMsg.backgroundColor+' transparent transparent #'+ chatMsg.backgroundColor+'; :'+ '':''"></div>
                        <div class="chat_content_text" v-html="chatMsg.message"></div>
                        <!-- 机器人活动商品 -->
                        <div v-show="chatMsg.recommend_goods" v-for="(recommendGoodsItem, index) in chatMsg.recommend_goods" :key="index" class="recommend">
                          <a :href="recommendGoodsItem.link">{{recommendGoodsItem.name}}</a>
                        </div>
                        <div v-show="chatMsg.recommend_activities" v-for="(recommendActivitiesItem, index) in chatMsg.recommend_activities" :key="index" class="recommend">
                          <a :href="recommendActivitiesItem.link">{{recommendActivitiesItem.name}}</a>
                        </div>
                        <span v-show="tabType === 'webchat_todo'" class="img_action_kmsearch iconfont icon-sousuo" @click.stop="openPopSearch({flag: true,data: chatMsg.message}, $event)"></span>
                      </div>
                      <!-- 机器人常见问题列表推送 -->
                      <div v-if="chatMsg.contentType === 'NewPushQues'" class="chat_content" :style="(chatMsg.isExistFocusWords && chatMsg.type === 'in')?'background-color:#'+ chatMsg.backgroundColor:''" :class="chatMsg.type === 'in' && tabType === 'webchat_todo' ? 'do_search' : ''">
                        <div class="chat_content_text" v-html="chatMsg.message"></div>
                      </div>
                      <!-- 机器人发出表单 -->
                      <div v-if="chatMsg.contentType === 'xbotFormSubmit'" class="chat_content" :style="(chatMsg.isExistFocusWords && chatMsg.type === 'in')?'background-color:#'+ chatMsg.backgroundColor:''" :class="chatMsg.type === 'in' && tabType === 'webchat_todo' ? 'do_search' : ''">
                        <div v-for="(formInfoLi, index) in chatMsg.xbotFormSubmit.formInfo" :key="index">
                          <p v-if="formInfoLi.type !== 'document'">{{formInfoLi.name}}：{{formInfoLi.value}}</p>
                          <div v-if="formInfoLi.type === 'document'">
                            {{formInfoLi.name}}：
                            <a v-for="(fileListLi, num) in formInfoLi.filelist" :key="num" :href="fileListLi.url" target='_blank'>{{fileListLi.name}}</a>
                          </div>
                        </div>
                      </div>
                      <!-- 访客填写机器人表单 -->
                      <div v-if="chatMsg.contentType === 'xbotForm'" class="chat_content">
                        <div class="chat_content_text" v-html="chatMsg.message"></div>
                      </div>
                      <!-- 表单消息 -->
                      <div v-if="chatMsg.contentType === 'sessionForm'" class="chat_content" :style="(chatMsg.isExistFocusWords && chatMsg.type === 'in')?'background-color:#'+ chatMsg.backgroundColor:''" :class="chatMsg.type === 'in' && tabType === 'webchat_todo' ? 'do_search' : ''">
                        <div :class="chatMsg.type === 'out' ? 'chat_content_arrow_out' : 'chat_content_arrow'" :style="(chatMsg.isExistFocusWords&&chatMsg.type === 'in')?'border: 5px solid #'+ chatMsg.backgroundColor+';border-color: #'+chatMsg.backgroundColor+' transparent transparent #'+ chatMsg.backgroundColor+'; :'+ '':''"></div>
                        <div class="chat_content_text">{{chatMsg.message}}</div>
                        <div v-show="chatMsg.recommend_activities" v-for="(recommendActivitiesItem, index) in chatMsg.recommend_activities" :key="index" class="recommend">
                          <a :href="recommendActivitiesItem.link">{{recommendActivitiesItem.name}}</a>
                        </div>
                      </div>
                      <!-- 图片 -->
                      <div v-if="chatMsg.contentType === 'image'" class="chat_content image">
                        <div :class="chatMsg.type === 'out' ? 'chat_content_arrow_out' : 'chat_content_arrow'"></div>
                        <!-- 展示视频或者图片或者链接 -->
                        <video v-if="fileType.includes((chatMsg.message.substring(chatMsg.message.lastIndexOf('.')+1)).toLowerCase())" :src="common.addCosDown(chatMsg.message, true)" width="230px" height="100%" controls></video>
                        <webchat-big-image
                          v-else
                          @click="currentImgUrl = common.urlDeal(chatMsg.message)"
                          :class="'chat_img ' + imageLoadClass(chatMsg._id)"
                          :msgId="chatMsg.when + ''"
                          :z-index="9999"
                          @imageLoadError="imageLoadError"
                          :message="chatMsg.message"
                          :chatMsgId="chatMsg._id"
                          :src="common.urlDeal(chatMsg.message)"
                          :preview-src-list="imageUrls">
                        </webchat-big-image>
                        <!-- <a v-else style="text-decoration:underline" :class="chatMsg.type === 'out' ? 'chat_content_text':'chat_message_con_text'" :href="common.addCosDown(chatMsg.message, true)" target="_blank">{{chatMsg.message}}</a> -->
                      </div>
                      <!-- 文件 -->
                      <div v-if="chatMsg.contentType === 'file' && !chatMsg.mp3Suffix" class="chat_content" :class="chatMsg.type === 'in' && tabType === 'webchat_todo' ? 'do_search' : ''" >
                        <div :class="chatMsg.type === 'out' ? 'chat_content_arrow_out' : 'chat_content_arrow'"></div>
                        <!-- {{chatMsg.message.substr(chatMsg.message.lastIndexOf(".")+1)}} -->
                        <!-- 此结构更改需谨慎，会影响kmSearch -->
                        <!-- 展示视频或者图片或者链接 -->
                        <video v-if="fileType.includes(chatMsg.fileName ? ((chatMsg.fileName.substring(chatMsg.fileName.lastIndexOf('.')+1)).toLowerCase()) : '')" :src="common.addCosDown(chatMsg.message, true)" width="230px" height="100%" controls></video>
                         <webchat-big-image
                          @click="currentImgUrl = common.urlDeal(chatMsg.message)"
                          v-else-if="imgType.includes(chatMsg.fileName ? ((chatMsg.fileName.substring(chatMsg.fileName.lastIndexOf('.')+1)).toLowerCase()) : '')"
                          :class="'chat_img ' + imageLoadClass(chatMsg._id)"
                          :msgId="chatMsg.when + ''"
                          :z-index="9999"
                          @imageLoadError="imageLoadError"
                          :message="chatMsg.message"
                          :chatMsgId="chatMsg._id"
                          :src="common.urlDeal(chatMsg.message)"
                          :preview-src-list="imageUrls">
                        </webchat-big-image>
                        <a v-else style="text-decoration:underline" :class="chatMsg.type === 'out' ? 'chat_content_text':'chat_message_con_text'" :href="common.addCosDown(chatMsg.message, true)" target="_blank">{{chatMsg.fileName}}</a>
                        <span v-show="tabType === 'webchat_todo'" class="img_action_kmsearch iconfont icon-sousuo" @click.stop="openPopSearch({flag: true,data: chatMsg.fileName}, $event)"></span>
                      </div>
                      <!-- 语音 -->
                      <div v-if="chatMsg.contentType === 'voice' || (chatMsg.contentType === 'file' && chatMsg.mp3Suffix)">
                        <div class="chat_text_con clearBoth">
                          <div class="chat_content voice_content">
                            <!--<div class="voice_content_cover" @click="playVoice($event)"></div>-->
                            <div :class="chatMsg.type === 'out' ? 'chat_content_arrow_out' : 'chat_content_arrow'"></div>
                            <div class="chat_message_con voiceMessage">
                              <span @click="changeVoicePlay(chatMsg, 'user')">
                                <webchat-chat-voice :chatMsg="chatMsg" :chatFlag="'user'" :style="{float: chatMsg.type === 'in' ? 'left' : 'right'}"></webchat-chat-voice>
                              </span>
                              <i 
                                v-if="!(chatMsg.voiceMsg || chatMsg.isFinish) && !(chatMsg.contentType === 'file' && chatMsg.mp3Suffix)"
                                class="iconfont icon-zhuanwenben1 voiceToTextIcon"
                                :class="chatMsg.type === 'in' ? 'voiceToTextIn' : 'voiceToTextOut'"
                                @click="voiceToText(chatMsg)">
                              </i>
                            </div>
                          </div>
                        </div>
                        <div v-if="chatMsg.voiceMsg || chatMsg.isFinish" class="voiceToTextBox">
                          <div class="chat_content_text" v-html="chatMsg.voiceMsg"></div>
                          <div class="voiceToTextSending" v-show="!chatMsg.voiceMsg"></div>
                        </div>
                      </div>
                      <!-- 视频 -->
                      <div v-if="chatMsg.contentType === 'video'" class="chat_content">
                        <div :class="chatMsg.type === 'out' ? 'chat_content_arrow_out' : 'chat_content_arrow'"></div>
                        <div class="chat_message_con" :class="{colorred:chatMsg.videoStatus === 'cancel' || chatMsg.videoStatus === 'refuse' || !chatMsg.videoStatus}">
                          <i class="iconfont icon-shipin" :class="{colorred:chatMsg.videoStatus === 'cancel' || chatMsg.videoStatus === 'refuse' || !chatMsg.videoStatus}"></i>
                          <span>{{VideoDesc(chatMsg.videoStatus)}}</span>
                          <span v-if="chatMsg.videoStatus === 'Hangup' || chatMsg.videoStatus === 'hangup'">{{videoTimeCom(chatMsg.message)}}</span>
                        </div>
                      </div>
                      <!-- 屏幕分享 -->
                      <div v-if="chatMsg.contentType === 'screenShare'" class="chat_content">
                        <div :class="chatMsg.type === 'out' ? 'chat_content_arrow_out' : 'chat_content_arrow'"></div>
                        <div class="chat_message_con" :class="{colorred:chatMsg.screenShareStatus === 'agentCancel' || chatMsg.screenShareStatus === 'custRefuse' || !chatMsg.screenShareStatus}">
                          <i class="iconfont icon-zhuomianfenxiang cursorpointer" @click="openScreenShareReplay(chatMsg)" :class="{colorred:chatMsg.screenShareStatus === 'agentCancel' || chatMsg.screenShareStatus === 'custRefuse' || !chatMsg.screenShareStatus}"></i>
                          <span>&nbsp; {{screenShareDesc(chatMsg.screenShareStatus)}}</span>
                          <span v-if="chatMsg.screenShareStatus === 'agentFinish'">{{videoTimeCom(chatMsg.duration)}}</span>
                        </div>
                      </div>
                      <!-- 微信分享地址 -->
                      <div class="chat_content" v-if="chatMsg.contentType === 'link'">
                        <div class="chat_content_arrow"></div>
                        <a class="link_title" :href="chatMsg.message" target="_blank">{{chatMsg.linkTitle}}</a>
                        <div class="link_description">{{chatMsg.linkDescription}}</div>
                      </div>
                      <!-- 微信小视频 -->
                      <div class="chat_content" v-if="chatMsg.contentType === 'wechatvideo'">
                        <div :class="chatMsg.type === 'out' ? 'chat_content_arrow_out' : 'chat_content_arrow'"></div>
                        <div class="chat_message_con wechat_video" @click="openWechatVideo(chatMsg)" >
                          <div class="wechat_video_play_icon">
                            <div class="play_icon"></div>
                          </div>
                          <img v-if="chatMsg.thunmbnail" class="wecbat_video_thunmbnail" :src="chatMsg.thunmbnail">
                          <div v-else class="wecbat_video_thunmbnail_no">
                            <div class="thunmbnail_no_icom"></div>
                          </div>
                        </div>
                      </div>
                      <!--商品信息-->
                      <div class="chat_msg_goods_info" v-if="isEcommerce && chatMsg.contentType === 'cardInfo'">
                        <div class="ecommerceCardInfo">
                          <img :src="chatMsg.cardInfo.imageUrl" alt="" class="ecommerceCardInfoImg">
                          <div class="ecommerceCardInfoRight">
                            <div class="ecommerceCardInfoTitle">{{chatMsg.cardInfo.name}}</div>
                            <div class="ecommercePrice">{{chatMsg.cardInfo.price}}</div>
                          </div>
                        </div>
                      </div>
                      <div class="chat_msg_goods_info" v-if="!isEcommerce && chatMsg.contentType === 'cardInfo'">
                        <div class="m7GoodsInfo" @click="openGoodsInfoUrl(chatMsg)">
                          <div class="goodInfoLeft" v-if="chatMsg.cardInfo.left && chatMsg.cardInfo.left.url">
                            <img :src="decodeURIComponent(chatMsg.cardInfo.left.url)">
                          </div>
                          <div class="goodInfoRight" :style="{width: chatMsg.cardInfo.left && chatMsg.cardInfo.left.url ? 'calc(100% - 70px)' : '100%'}">
                            <span class="goodInfoRight1" v-if="chatMsg.cardInfo.right1 && chatMsg.cardInfo.right1.text">{{chatMsg.cardInfo.right1.text}}</span>
                            <span class="goodInfoRight2" v-if="chatMsg.cardInfo.right2 && chatMsg.cardInfo.right2.text">{{chatMsg.cardInfo.right2.text}}</span>
                            <span class="goodInfoRight3" v-if="chatMsg.cardInfo.right3 && chatMsg.cardInfo.right3.text">{{chatMsg.cardInfo.right3.text}}</span>
                            <span class="MoreGoodsInfo" v-if="chatMsg.cardInfo.extraInfos && chatMsg.cardInfo.extraInfos.length > 0" v-html="showExtraInfoMap[chatMsg._id] ? '收起' : '更多'" @click.stop="showExtraInfo(chatMsg, index)"></span>
                            <span v-if="chatMsg.cardInfo.extraInfos && chatMsg.cardInfo.extraInfos.length > 0 && showExtraInfoMap[chatMsg._id]" v-for="moreInfo in chatMsg.cardInfo.extraInfos">{{moreInfo}}</span>
                          </div>
                        </div>
                      </div>
                      <!--微信小程序卡片消息-->
                      <div class="chat_msg_miniprog_info" v-if="chatMsg.contentType === 'miniprogrampage'">
                        <div class="miniprogInfo">
                          <div class="miniprogTitle">
                            <span style="white-space: normal;word-break: break-all" class="goodInfoRight1" v-show="chatMsg.miniCardInfo && chatMsg.miniCardInfo.title">{{chatMsg.miniCardInfo.title}}</span>
                          </div>
                          <div class="miniprogImg" v-if="chatMsg.miniCardInfo && chatMsg.miniCardInfo.picUrl">
                            <img :src="decodeURIComponent(chatMsg.miniCardInfo.picUrl)">
                          </div>
                        </div>
                        <div>
                          <i class="im_wxminiIcon"></i><span>{{$t('webchat.weChatMini')}}</span>
                        </div>
                      </div>
                      <!--商品卡片信息消息-->
                      <div class="chat_msg_newCardInfo" :style="{marginRight: chatMsg.type === 'out' ? '5px': ''}" v-if="chatMsg.contentType === 'newCardInfo' && chatMsg.newCardInfo">
                        <div @click="openGoodsInfoUrl(chatMsg)">
                          <div :class="chatMsg.type === 'out' ? 'chat_cardInfo_arrow_out' : 'chat_cardInfo_arrow'"></div>
                          <div class="chat_msg_newCardInfo_top">
                            <img :src="chatMsg.newCardInfo && chatMsg.newCardInfo.img" alt="">
                            <div class="newCardInfo_top_right">
                              <div class="newCardInfoTitle">{{chatMsg.newCardInfo.title}}</div>
                              <div class="newCardInfoSecond">
                                <p :class="{newCardInfoSubTitle: chatMsg.newCardInfo.price || chatMsg.newCardInfo.attr_two, newCardInfoSubTitleTwo: !(chatMsg.newCardInfo.price || chatMsg.newCardInfo.attr_two)}"
                                   v-show="chatMsg.newCardInfo.sub_title" :style="{width: chatMsg.newCardInfo.attr_one ? '160px' : '210px', float: 'left'}">
                                  {{chatMsg.newCardInfo.sub_title}}
                                </p>
                                <p class="newCardInfoAttrOne" :style="{color: chatMsg.newCardInfo.attr_one && chatMsg.newCardInfo.attr_one.color || '#878787'}" v-if="chatMsg.newCardInfo.attr_one">{{chatMsg.newCardInfo.attr_one.content}}</p>
                              </div>
                              <div>
                                <p v-show="chatMsg.newCardInfo.price" class="newCardInfoPrice">{{chatMsg.newCardInfo.price}}</p>
                                <p class= "newCardInfoAttrTwo" :style="{color: chatMsg.newCardInfo.attr_two && chatMsg.newCardInfo.attr_two.color || '#FF8403'}" v-if="chatMsg.newCardInfo.attr_two">{{chatMsg.newCardInfo.attr_two.content}}</p>
                              </div>
                            </div>
                          </div>
                          <div class="newCardInfoDecs">
                            <p v-show="chatMsg.newCardInfo.other_title_one">{{chatMsg.newCardInfo.other_title_one}}</p>
                            <p v-show="chatMsg.newCardInfo.other_title_two">{{chatMsg.newCardInfo.other_title_two}}</p>
                            <p v-show="chatMsg.newCardInfo.other_title_three">{{chatMsg.newCardInfo.other_title_three}}</p>
                          </div>
                        </div>
                        <div v-if="chatMsg.newCardInfo.tags && chatMsg.newCardInfo.tags.length > 0" class="newCardInfoBtn">
                          <ul>
                            <li v-for="(item, index) in chatMsg.newCardInfo.tags" :key="index"><el-button size="mini" :type="index === 0 ? 'primary' : ''" @click.native="jumpIframeFun(item)" v-if="item.label">{{item.label}}</el-button></li>
                          </ul>
                        </div>
                      </div>
                      <!-- xbot机器人商品信息卡片消息 -->
                      <div class="chat_msg_newCardInfo robot_cardinfo" :style="{marginRight: chatMsg.type === 'out' ? '5px': ''}" v-if="(chatMsg.contentType === 'msgTask' || chatMsg.msgType === 'msgTask' ) && chatMsg.newCardInfo">
                        <div @click="openGoodsInfoUrl(chatMsg)">
                          <div :class="chatMsg.type === 'out' ? 'chat_cardInfo_arrow_out' : 'chat_cardInfo_arrow'"></div>
                          <div class="chat_msg_newCardInfo_top">
                            <img :src="chatMsg.newCardInfo && chatMsg.newCardInfo.img" alt="">
                            <div class="newCardInfo_top_right">
                              <div class="newCardInfoTitle clearfix">
                                <p class="robotCardInfoCon">{{chatMsg.newCardInfo.title}}</p>
                                <p v-show="chatMsg.newCardInfo.price" class="newCardInfoPrice">{{chatMsg.newCardInfo.price}}</p>
                              </div>
                              <div class="newCardInfoSecond">
                                <p :class="{newCardInfoSubTitle: chatMsg.newCardInfo.price || chatMsg.newCardInfo.attr_two, newCardInfoSubTitleTwo: !(chatMsg.newCardInfo.price || chatMsg.newCardInfo.attr_two)}"
                                   v-show="chatMsg.newCardInfo.sub_title" :style="{width: chatMsg.newCardInfo.attr_one ? '160px' : '210px', float: 'left'}">
                                  {{chatMsg.newCardInfo.sub_title}}
                                </p>
                                <p class="newCardInfoAttrOne" :style="{color: chatMsg.newCardInfo.attr_one && chatMsg.newCardInfo.attr_one.color || '#878787'}" v-if="chatMsg.newCardInfo.attr_one">{{chatMsg.newCardInfo.attr_one.content}}</p>
                              </div>
                              <div class="robotCardInfoThird">
                                <p class= "robotCardInfoThirdLeft" v-show="chatMsg.newCardInfo.other_title_one">{{chatMsg.newCardInfo.other_title_one}}</p>
                                <p class= "newCardInfoAttrTwo" :style="{color: chatMsg.newCardInfo.attr_two && chatMsg.newCardInfo.attr_two.color || '#FF8403'}" v-if="chatMsg.newCardInfo.attr_two">{{chatMsg.newCardInfo.attr_two.content}}</p>
                              </div>
                            </div>
                          </div>
                        </div>
                        <div v-if="chatMsg.newCardInfo.tags && chatMsg.newCardInfo.tags.length > 0" class="newCardInfoBtn">
                          <ul>
                            <li v-for="(item, index) in chatMsg.newCardInfo.tags" :key="index"><el-button size="mini" :type="index === 0 ? 'primary' : ''" @click.native="jumpIframeFun(item)" v-if="item.label">{{item.label}}</el-button></li>
                          </ul>
                        </div>
                      </div>
                      <!--商品卡片信息消息-->
                      <div class="chat_msg_newCardInfo" :style="{marginRight: chatMsg.type === 'out' ? '5px': ''}" v-if="chatMsg.contentType === 'ecommerceOrderCardInfo'">
                        <orderInfoCard :goodsInfo="chatMsg.cardInfo"></orderInfoCard>
                      </div>
                      <!--xbot卡片信息-->
                      <div v-if="chatMsg.contentType === 'msgTask' && !chatMsg.newCardInfo">
                        <div class="chat_content">
                          <div :class="chatMsg.type === 'out' ? 'chat_content_arrow_out' : 'chat_content_arrow'" :style="(chatMsg.isExistFocusWords&&chatMsg.type === 'in')?'border: 5px solid #'+ chatMsg.backgroundColor+';border-color: #'+chatMsg.backgroundColor+' transparent transparent #'+ chatMsg.backgroundColor+'; :'+ '':''"></div>
                          <div class="chat_content_text">
                            {{chatMsg.message}}
                          </div>
                        </div>
                      </div>
                      <!-- iframe -->
                      <div v-if="chatMsg.contentType === 'iframe'" class="chat_content">
                        <div class="chat_content_arrow_out"></div>
                        <iframe sandbox="allow-scripts allow-same-origin allow-popups allow-forms allow-pointer-lock allow-modals allow-forms allow-presentation" :src="newUrl(chatMsg.message)" frameborder="0" :width="(chatMsg.iframeWidth <=280 ?chatMsg.iframeWidth : 280)" :height="chatMsg.iframeHeight"></iframe>
                      </div>
                      <!--富文本链接-->
                      <div v-if="chatMsg.contentType === 'richText'" class="chat_content">
                        <div class="chat_content_arrow_out"></div>
                        <div class="chat_msg_richText" @click.stop="openNewRichText(chatMsg.richTextUrl)">
                          <p class="richTextTitle">{{chatMsg.richTextTitle}}</p>
                          <div class="chat_msg_richText_bottom">
                            <p class="richTextDescription" :style="{width: chatMsg.richTextPicUrl ? '140px' : ''}">{{chatMsg.richTextDescription}}</p>
                            <img v-if="chatMsg.richTextPicUrl" :src="chatMsg.richTextPicUrl" class="richTextPicUrl">
                          </div>
                        </div>
                      </div>
                      <!-- 小程序微信消息发送状态框 -->
                      <el-tooltip v-if="chatMsg.type === 'in' && (chatMsg.platform === 'wxmini' || chatMsg.platform === 'weixin') && chatMsg.wechatGetImageError" :content="errorCodeFun('weixinCodeError')" placement="right">
                        <div class="chat_send_status_in fail">
                          <span class="shield_chat_arrow"></span>
                        </div>
                      </el-tooltip>
                      <el-tooltip v-if="chatMsg.type === 'in' && (chatMsg.platform === 'dy' || chatMsg.platform === 'wxkf') && chatMsg.wechatGetImageError" :content="errorCodeFun(chatMsg)" placement="right">
                        <div class="chat_send_status_in fail">
                          <span class="shield_chat_arrow"></span>
                        </div>
                      </el-tooltip>
                      <!-- 头像 -->
                      <div :class="chatMsg.type === 'out' ? 'chat_user_info_out clearBoth' : 'chat_user_info'">
                        <div v-if="chatMsg.type === 'out'" :class="{robot: chatMsg.im_src === 'robot', chat_user_img: !chatMsg.im_src, chat_user_gif: chatMsg.im_src, backgroundNone: chatInfo.systemMsgLogo}">
                          <img v-if="chatMsg.im_src && chatMsg.im_src != 'robot'"
                               :src="filterImag(chatMsg.im_src, index, 'current')"
                               @mouseenter="changeImgEnter(chatMsg.im_src, $event)"
                               @mouseleave="changeImgLeave(chatMsg.im_src, $event)"
                               alt=""/>
                          <img v-if="chatMsg.user === 'system' && chatInfo.systemMsgLogo"  :src="chatInfo.systemMsgLogo" alt=""/>
                          <i v-if="chatMsg.im_src === 'robot'" class="iconfont robot_default icon-jiqirentouxiang"></i>
                        </div>
                        <div class="client_msg" v-else>
                            <img :src="chatInfo.headUrl" alt="" class="weixinHead"
                                 v-if="chatInfo.headUrl && chatInfo.headUrl !== ''">
                            <span class="weixinHead defaultHead" v-else><i class="iconfont icon-fangkeduanyonghutouxiang"></i></span>
                        </div>
                        <div class="chat_time">{{chatTime(chatMsg)}}</div>
                      </div>
                    </div>
                    <div class="clearBoth"></div>
                    <!-- 表单消息附带的系统消息，特殊的系统消息,需要单独展示 -->
                    <div class="chat_item system clearBoth sessionForm" v-if="chatMsg.contentType === 'sessionForm'">
                      <div class="chat_content">
                        {{(chatMsg.dateTime ? chatMsg.dateTime : '')  + ' ' + $t('webchat.formMsgTitle', {message: chatMsg.sessionForm ? (chatMsg.sessionForm.formName || '') : ''})}}
                      </div>
                    </div>
                    <div class="historyDivied" v-if="index < messageList.length - 1 && chatMsg.sessionId && messageList[index + 1].sessionId && (chatMsg.sessionId !== messageList[index + 1].sessionId)">
                      <span class="divided_text">
                        <span class="divided_line_left"></span>
                        {{$t('webchat.historyNews')}}
                        <span class="divided_line_right"></span>
                      </span>
                    </div>
                  </div>
                  <!-- 会话展示重构 070919 by liujing -->
                  <div v-if="uploaded.uploadImg && uploaded.uploadImgSessionId === sessionId" class="uploaded msg_li clearBoth">
                    <div class="chat_item out clearBoth">
                      <div class="chat_content image">
                        <div class="chat_content_arrow_out"></div>
                        <div class="uploadingImg"></div>
                      </div>
                      <div class="chat_user_info_out clearBoth">
                        <div class="chat_user_img" :class="{robot: chatInfo.im_src === 'robot'}">
                          <img v-if="chatInfo.im_src &&  chatInfo.im_src != 'robot'"
                               :src="filterImag(chatInfo.im_src, 0, 'upload')"
                               @mouseenter="changeImgEnter(chatInfo.im_src, $event)"
                               @mouseleave="changeImgLeave(chatInfo.im_src, $event)"
                               alt=""/>
                          <i v-if="chatInfo.im_src === 'robot'" class="iconfont robot_default icon-jiqirentouxiang"></i>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div v-if="uploaded.uploadFile.flag && uploaded.uploadFile.uploadFileSessionId === sessionId" class="uploaded msg_li clearBoth">
                    <div class="chat_item out clearBoth">
                      <!-- 重新发送按钮 -->
                      <div class="resend" v-if="uploaded.uploadFile.progress == $t('webchat.uploadError')"><i class="el-icon-refresh-right" @click="reSend"></i></div>
                      <div class="chat_content">
                        <div class="chat_content_arrow_out"></div>
                        <div class="upload_file_box">
                          <div class="upload_file_title">{{uploaded.uploadFile.name}}</div>
                          <div class="upload_file_progress_title">{{uploaded.uploadFile.progress}}</div>
                          <div class="upload_file_progress">
                            <span class="file_progress" :style="'width:' + uploaded.uploadFile.progress"></span>
                          </div>
                        </div>
                      </div>
                      <div class="chat_user_info_out clearBoth">
                        <div class="chat_user_img" :class="{robot: chatInfo.im_src === 'robot'}">
                          <img v-if="chatInfo.im_src && chatInfo.im_src != 'robot'"
                               :src="filterImag(chatInfo.im_src, 0, 'upload')"
                               @mouseenter="changeImgEnter(chatInfo.im_src, $event)"
                               @mouseleave="changeImgLeave(chatInfo.im_src, $event)"
                               alt=""/>
                          <i v-if="chatInfo.im_src === 'robot'" class="iconfont robot_default icon-jiqirentouxiang"></i>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
                <div class="chatPreloadedMsg chat_item in clearBoth" v-show="preloadedFlag">  <!--chatInfoById.showChatPreloaded-->
                  <div class="chat_user_info">
                    <div class="client_msg">
                      <img :src="chatInfo.headUrl" alt="" class="weixinHead"
                           v-if="chatInfo.headUrl && chatInfo.headUrl !== ''">
                      <span class="weixinHead defaultHead" v-else><i class="iconfont icon-fangkeduanyonghutouxiang"></i></span>
                    </div>
                    <div class="chat_time" v-text="preloadedTitle ? $t('webchat.inviteStatusTyping') : $t('webchat.inviteStatusTyp')"></div>
                  </div>
                  <div class="chat_content" >
                    <div class="chat_content_arrow"></div>
                    <div class="chat_message_con" v-html="preloadedMsgCon"></div><!-- preloadedMsgCon 预加载的消息 -->
                  </div>
                </div>
              </div>
              <transition name="fade">
                <div class="chatNewStashMsg" v-show="holdNewMsg.Show" @click.stop="showHoldNewMsg">
                  <div class="stash_arrow_left"></div>
                  <p v-html="holdNewMsg.Msg">
                  </p>
                </div>
              </transition>
              <transition name="fade">
                <div class="chatStashNum"  v-show="holdNewMsg.Num > 0" @click.stop="showHoldNewMsgId">
                  <p><span class="icon-xiangxiashuangjiantou iconfont" style="font-size: 12px"></span>{{holdNewMsg.Num}}{{$t('webchat.news')}}</p>
                </div>
              </transition>
            </div>
            <div class="leaveMsgNotice" v-show="isLeaveMsg">
              <p>
                {{$t('sms.attention')}}
                <span class="leveaClose" @click="leaveCloseFun('leaveMsg')">×</span>
              </p>
              <p v-show="isLeaveMsg">{{$t('webchat.leaveMsgNotice')}}</p>
            </div>
            <div class="leaveMsgNotice" v-show="isActiveSession && !isEcommerce">
              <p>
                {{$t('sms.attention')}}
                <span class="leveaClose" @click="leaveCloseFun('activeSession')">×</span>
              </p>
              <p v-show="isActiveSession">{{$t('webchat.activeSessionNotice')}}</p>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>
<script type="text/javascript">
  import bus from '@/store/eventBus'
  import { common } from '@/utils/cosUrl'
  import * as webchatUtils from '@/utils/webchat.js'
  import webchatBigImage from '@/components/ui-modules/image/src/webchatBigImage'
  import {deepClone, getCache, innerHtmlChannelColor, filterXSS, contains} from '@/utils/m7Utils'
  import * as types from '@/store/modules/webchat/mutation-types.js'
  import * as typesOn from '@/store/mutation-types.js'
  import WebchatChatVoice from './WebchatChatVoice.vue'
  import orderInfoCard from '@/components/business-modules/webchat/base/orderInfoCard'
  export default {
    name: 'WebchatConMsgBox',
    props: {
      chatMsgCon: Object,
      uploaded: Object,
      expandLayout: Boolean,
      initiativeSession: Boolean,
      id: String,
      message: Array,
    },
    data () {
      return {
        lastPlayTime: 0,    // 语音消息的上次点击时间
        currentTime: 0,      // 语音消息的本次点击时间
        preloadedTitle: true,   // 预加载消息框的提示语
        loadFlag: true,  // 加载历史flag
        AvatarList: [],     // 头像地址缓存数组
        videoRecordStatus: '',  // 是否开启视频录制
        holdNewMsg: {
          Show: false,          // 滚动条至上方时，新消息做预览显示
          Msg: '',              // 最新消息
          MsgId: '',            // 第一条最新消息的id
          Num: 0,               // 预览消息条数
          TimeOut: 0            // 隐藏预览消息的延迟id
        },
        MsgBoxScrollTarget: -1, // 滚动行为目标值
        leaveMsgIsClose: true, // 留言提示是否关闭
        activeSessionIsclose: true, // 主动会话提示是否关闭
        showExtraInfoMap: {},    // 缓存商品信息卡片更多信息展示
        currentImgUrl: '', // 记录当前点击的图片
        isEcommerce: this.$store.getters.isEcommerce ? true : false,
        isShowDealMsgStatus: false,
        CSRShowToAgent: 'all',
        imageLoadErrorArr: [],  // 记录当前会话列表中图片消息加载失败的消息ID
        sdkVcode: false,
        common,
        reSendFile:null,
        fileType:['mp4', 'f4v', 'm4v', 'mkv', 'mov', 'webm'],
        imgType:['jpe', 'jpeg', 'jpg', 'gif', 'png','heic','webp','bmp','ico','tif','jfif']
      }
    },
    methods: {
      // 重新发送
      reSend(){
        bus.$emit('toResendMsg', this.reSendFile)
      },
      showExtraInfo (msg) {
        if (this.showExtraInfoMap[msg._id] !== undefined) {
          this.showExtraInfoMap[msg._id] = !this.showExtraInfoMap[msg._id]
        } else {
          this.$set(this.showExtraInfoMap, msg._id, false)
        }
      },
      handleWinFocus () {
        let currentRoute = this.$route.path.split('/')
        if (currentRoute && currentRoute.indexOf('webchat_todo') > -1) {
          this.dealMsgFun()
        }
      },
      leaveCloseFun (type) {
        if (type === 'leaveMsg') {
          this.leaveMsgIsClose = false
        } else {
          this.activeSessionIsclose = false
        }
      },
      imageLoadError (data) {
        if (data && data !== 'undefined' && this.imageLoadErrorArr.indexOf(data) === -1) {
          this.imageLoadErrorArr.push(data)
        }
      },
      errorCodeFun (errcode) {  // 小程序客服&&抖音客服错误码&&微信官方客服错误码
        let errorMsg = ''
        let errorType
        if (errcode.platform === 'weixin') {
          errorType = errcode.weixinres
        } else if (errcode.platform === 'dy' || errcode.platform === 'wxkf') {
          errorType = errcode.sendRes
        } else {
          errorType = errcode.wxminires
        }
        if (typeof errorType === 'object') {
          errorMsg = 'webchat.errorCode.errcode_' + errorType.code
        } else if (errorType === 'weixinCodeError') {
          errorMsg = 'webchat.errorCode.errcode_40001_new'
        } else {
          if (errcode.platform === 'weixin' && errorType === 45047) {
            errorMsg = 'webchat.errorCode.errcode_' + errorType + '_weixin'
          } else if (errcode.platform === 'dy') {
            errorMsg = 'webchat.dyErrorCode.dyerrcode_' + errorType
          } else if (errcode.platform === 'wxkf') {
            errorMsg = 'webchat.wxkfErrorCode.wxkferrcode_' + errorType 
          } else {
            errorMsg = 'webchat.errorCode.errcode_' + errorType
          }
        }
        return this.$t(errorMsg)
      },
      openNewRichText (url) {
        if (url) {
          window.open(url)
        }
      },
      shieldClick (data, event) {
        console.log(event)
        let that = this
        that.shieldMsg = deepClone(data)
        let newData = {
          sid: that.webchatData.sid,
          _id: data.messageId || data._id // 处理app端发送消息 pc端无法撤回
        }
        this.$store.dispatch('withdrawMessage', newData).then((response) => {
          if (response.success) {
            // 消息撤回成功
            that.$set(that.shieldMsg, 'syncUser', true)
            if (data.messageId) { // 处理app端发送消息 pc端无法撤回
              that.$store.commit(types.SHIELD_MSG, {data: that.shieldMsg, message: that.$t('webchat.ShieldMsg'), flag: true})
            } else {
              that.$store.commit(types.SHIELD_MSG, {data: that.shieldMsg, message: that.$t('webchat.ShieldMsg')})
            }
          } else if (response.message === 'webchat_cannot_withdraw_msg_before_two_min') {
            that.$message.error(this.$t('message.webchat_cannot_withdraw_msg_before_two_min'))
          } else if (response.message === 'webchat_message_not_fount') {
            that.$message.error(this.$t('message.webchat_message_not_fount'))
            that.$store.commit(types.DELETE_MESSAGE, {data: that.shieldMsg, message: that.$t('webchat.ShieldMsg')})
          }
        })
      },
      withdrawReedit (data) {
        let now = new Date().getTime()
        if (!data.drawTime) {
          return
        }
        if (now - data.drawTime > 120000) {
          this.$message.error(this.$t('message.withdoawMsgTip'))
          return
        }
        bus.$emit('withdrawReedit', data)
      },
      jumpIframeFun (data) {
        bus.$emit('jumpIframeFun', data)
      },
      openVideoReplay (chatMsg) {
        if (!(chatMsg.videoStatus === 'Hangup' || chatMsg.videoStatus === 'hangup')) {
          return
        }
        if (!this.videoRecordStatus) {
          this.$message({
            message: this.$t('webchat.videoReplayNotOpen'),
            type: 'warning'
          })
          return
        }
        if (chatMsg.videoUrl && chatMsg.videoUrl !== '') {
          this.$emit('videoReplay', {url: chatMsg.videoUrl, ChatMsg: chatMsg})
        } else {
          let data = {
            _id: chatMsg.messageId || chatMsg._id,
            sid: chatMsg.sid
          }
          this.$store.dispatch('queryVideoReplayUrl', data).then(response => {
            if (response.videoUrl && response.videoUrl !== '') {
              this.$emit('videoReplay', {url: response.videoUrl, ChatMsg: chatMsg})
            } else {
              this.$message({
                message: this.$t('webchat.videoReplayNotDoneWarn'),
                type: 'warning'
              })
            }
          })
        }
      },
      openScreenShareReplay (chatMsg) {
        if (chatMsg.screenShareStatus !== 'agentFinish') {
          return
        }
        if (chatMsg.videoUrl && chatMsg.videoUrl !== '') {
          this.$emit('videoReplay', {url: chatMsg.videoUrl, ChatMsg: chatMsg})
        } else {
          let data = {
            _id: chatMsg.messageId || chatMsg._id,
            sid: chatMsg.sid
          }
          this.$store.dispatch('queryVideoReplayUrl', data).then(response => {
            if (response.videoUrl && response.videoUrl !== '') {
              this.$emit('videoReplay', {url: response.videoUrl, ChatMsg: chatMsg})
            } else {
              this.$message({
                message: this.$t('webchat.videoReplayNotDoneWarn'),
                type: 'warning'
              })
            }
          })
        }
      },
      trim (data) {
        let _str = data
        return _str.replace(/(^\s*)|(\s*$)/g, '')
      },
      getChatHistoryScroll (event) {
        // 滚动加载历史记录
        if (event.target.scrollTop < 2 && !this.chatInfo.finishChatScroll && this.loadFlag) {
          this.loadFlag = false
          this.MsgBoxScrollTarget = document.getElementsByClassName('msg_inner')[0].offsetHeight
          // 特殊情况下，卡片切换有滚动条的情况下，高度不一致会触发
          // let isHasScroll = document.getElementsByClassName('chat_msg')[0].clientHeight > document.getElementsByClassName('msg_inner')[0].clientHeight
          // 特殊情况下，messageList有可能为空，此处需要做判断处理一下
          if (this.messageList.length) {
            this.queryMessageHistory()
          } else {
            this.loadFlag = true
          }
        }
      },
      queryMessageHistory () {
        // 加载历史消息
        this.MsgBoxScrollTarget = document.getElementsByClassName('msg_inner')[0].offsetHeight
        let queryData = {
          sid: this.chatInfo.sid,
          when: this.messageList[0] ? this.messageList[0].when : new Date().getTime(),
          submenu: this.tabType,
          currentSessionId: this.chatInfo._id
        }
        if (!this.messageList[0]) {
          // 如果当前消息列表没有消息，传参让服务端从最新的开始找
          queryData.whenStartTag = new Date().getTime()
        }
        if (!this.chatInfo.showHistoryBtn) {
          // 滚动加载当前会话
          queryData.limit = 10
          queryData.sessionId = this.chatInfo._id
        } else {
          // 滚动加载历史会话
          queryData.limit = 50
        }
        this.$store.dispatch('queryMessageHistory', queryData).then(() => {
          // 22.9修复向上滑动有时候滑动不了，看不到历史消息问题
          // window.setTimeout(() => {
          if (this.MsgBoxScrollTarget > -1 && document.getElementsByClassName('chat_msg').length > 0) {
            this.$nextTick(() => {
              console.log('11111111')
              document.getElementsByClassName('chat_msg')[0].scrollTop = document.getElementsByClassName('msg_inner')[0].scrollHeight - this.MsgBoxScrollTarget - 40
              this.MsgBoxScrollTarget = -1
            })
          }
          // }, 0)
          this.loadFlag = true
        })
      },
      scrollToBottom (data) {
        this.$nextTick(function () {
          if (document.getElementsByClassName(data.scrollName).length) {
            document.getElementsByClassName(data.scrollName)[0].scrollTop = document.getElementsByClassName(data.warpName)[0].scrollHeight
          }
        })
      },
      showBigImage (data) {
        if (this.qualityCheck) {
          return
        }
        bus.$emit('webchatShowBigImage', data)
        // this.$emit('showBigImage', data)
        this.$nextTick(() => {
          let sendData = {url: data, list: this.imageUrls}
          bus.$emit('webchatShowBigImageData', sendData)
          let box = document.getElementById('bigImage')
          let width = document.body.clientWidth
          let height = document.body.clientHeight
          box.style.cssText = 'left:' + (width - box.clientWidth) / 2 + 'px;top:' + (height - box.clientHeight) / 2 + 'px'
        })
      },
      openPopSearch (obj, event) {
        window._hmt && window._hmt.push(['_trackEvent', '在线咨询', 'PM-聊天信息快捷搜索'])
        let dataNew = deepClone(obj)
        let objNew = event.target
        let parent = objNew.parentNode
        let data = parent.children[1].innerText
        let str = this.trim(data)
        dataNew.data = str
        console.log(dataNew)
        this.$emit('handleFullChat')
        bus.$emit('fastSearchWebchatContent', dataNew)
        // this.$emit('popSearchOpen', dataNew)
      },
      filterImIcon (obj, ishistory) {
        if (typeof obj === 'object') {
          if (obj.user && obj.user !== 'system' && obj.user !== 'robot') {
            let agent = getCache('agents', obj.user)
            if (this.isEcommerce) {
              if (obj.im_icon && obj.im_icon !== '') {
                obj.im_src = obj.im_icon + '?imageView2/1/w/50/h/50'
              } else {
                obj.im_src = ''
              }
            } else {
              if (agent.im_icon) {
                obj.im_src = agent.im_icon + '?imageView2/1/w/50/h/50'
                if (obj.contentType === 'video') {
                  obj.im_src = agent.im_icon + '?imageView2/1/w/50/h/50'
                }
              } else {
                obj.im_src = ''
              }
            }
          } else if (obj.user === 'robot') {
            obj.im_src = 'robot'
          } else if (obj.user === 'system' && obj.im_icon) {
            obj.im_src = obj.im_icon + '?imageView2/1/w/50/h/50'
          } else {
            obj.im_src = ''
          }
          if (ishistory) {
            let user = this.$store.state.session.user._id
            let time = new Date()
            let timeNow = time.getTime() + this.nowTime
            if (obj.when && timeNow - obj.when < 120000 && obj.when && obj.platform !== 'weibo' && obj.platform !== 'weixin' && obj.platform !== 'wxmini' && obj.platform !== 'ocpc' && obj.platform !== 'dy' && obj.platform !== 'wxkf' && obj.type === 'out' && obj.im_src !== 'robot' && this.tabType === 'webchat_todo' && user === obj.user && obj.contentType !== 'video') {
              this.$set(obj, 'tipDisabled', true)
            } else {
              this.$set(obj, 'tipDisabled', false)
            }
            let timeNew = ''
            if (obj.showTime) {
              timeNew += ` ${obj.showTime}`
            }
            if (obj.uidDesc) {
              timeNew += ` ${obj.uidDesc}`
            }
            obj.timeNew = timeNew
          }
        }
        return obj
      },
      chatTime (item) {
        let timeNew = ''
        if (item.showTime) {
          timeNew += ` ${item.showTime}`
        } else if (!item.showTime && item.createTime) {
          timeNew += ` ${item.createTime}`
        }
        if (item.uidDesc) {
          timeNew += ` ${item.uidDesc}`
        }
        return timeNew
      },
      changeVoicePlay (chatMsg, flag) {
        this.currentTime = Date.now()
        if ((this.currentTime - this.lastPlayTime) < 300) {
          return
        }
        let arr = this.$route.path.split('/')
        let tabType = arr[3]
        let _id = arr[4]
        if (!chatMsg.play) {
          this.$store.commit(types.RESET_USER_HISTORY_VOICE_PLAY, {tabType: tabType, _id: _id})
          this.$store.commit(types.SET_CHAT_VOICE_PLAY, {tabType: tabType, _id: _id, when: chatMsg.when, data: true, flag: flag})
        } else {
          this.$store.commit(types.SET_CHAT_VOICE_PLAY, {tabType: tabType, _id: _id})
          this.$store.commit(types.SET_CHAT_VOICE_PLAY, {tabType: tabType, _id: _id, when: chatMsg.when, data: false, flag: flag})
        }
        this.lastPlayTime = Date.now()
      },
      voiceToText (data) {
        let arr = this.$route.path.split('/')
        let tabType = arr[3]
        let _id = arr[4]
        let messageId = data.messageId || data._id
        let sendData = {
          accountId: data.account,
          userId: this.userId,
          messageId: messageId,
          chatSessionId: this.sessionId,
          sid: data.sid,
          filePath: data.message,
          tabType: tabType,
          when: data.when
        }
        this.$store.dispatch('webchatVoiceToText', sendData).then(res => {
          let voiceMsg = res.voiceMessage ? res.voiceMessage : ''
          this.$store.commit(types.VOICETOTEXT, {tabType: tabType, _id: _id, when: data.when, isFinish: true, voiceMsg: voiceMsg})
        })
      },
      VideoDesc (data) {
        if (data === 'cancel') {
          return this.$t('videoChat.videoHasBeenCancel')
        } else if (data === 'refuse') {
          return this.$t('videoChat.videoNotBeAnswer')
        } else if (data === 'Hangup' || data === 'hangup') {
          return this.$t('videoChat.videoTimeLength')
        } else {
          return this.$t('videoChat.videoHasBeenCancel')
        }
      },
      screenShareDesc (data) {
        if (data === 'agentCancel') {
          return this.$t('screenShare.shareHasBeenCancel')
        } else if (data === 'custRefuse') {
          return this.$t('screenShare.shareNotBeAnswer')
        } else if (data === 'agentFinish') {
          return this.$t('screenShare.shareTimeLength')
        } else {
          return this.$t('screenShare.shareHasBeenCancel')
        }
      },
      videoTimeCom (time) {
        var hours = Math.floor(time / (3600 * 1000))
        var hoursleft = time % (3600 * 1000)
        var minutes = Math.floor(hoursleft / (60 * 1000))
        var minutesleft = hoursleft % (60 * 1000)
        var seconds = Math.floor(minutesleft / 1000)
        if (seconds === 60) {
          minutes = minutes + 1
          seconds = 0
        }
        if (minutes === 60) {
          hours = hours + 1
          minutes = 0
        }
        var h = hours > 9 ? hours : '0' + hours
        var m = minutes > 9 ? minutes : '0' + minutes
        var s = seconds > 9 ? seconds : '0' + seconds
        return h + ':' + m + ':' + s
      },
      preloadedMsgConChange () {
        if (this.preloadedMsgCon && this.preloadedMsgCon !== 'undefined') {
          this.preloadedTitle = true
          let that = this
          setTimeout(function () {
            that.preloadedTitle = false
          }, 5000)
        } else {
          let arr = this.$route.path.split('/')
          let _id = arr[4]
          if (_id && this.tabType === 'webchat_todo') {
            this.$store.commit(types.UPDATE_PRELOADED_MSG_FLAG, {_id: _id, value: false})
          }
        }
      },
      newUrl (url) {
        return url.replace('http://', '//')
      },
      dealMsgFun () {
        let unReadMessageList = []
        this.messageList.map(item => {
          if (item.type === 'in' && !item.dealCustomerMsg) {
            unReadMessageList.push(item.messageId || item._id) 
          }
        })
        if (unReadMessageList.length > 0) {
          let sendData = {
            sid: this.chatInfo.sid,
            accessId: this.chatInfo.accessId,
            messageIdList: unReadMessageList,
            sessionId: this.sessionId
          }
          this.$store.dispatch('dealImMsgFromUser', sendData)
        }
      },
      fetchData () {
        // 切换卡片时获取聊天记录
        this.imageLoadErrorArr = []
        this.loadFlag = false
        if (this.$store.state.webchat.current.webchat_todo.messageList[this.sessionId] && this.tabType === 'webchat_todo') {
          let currentHistory = this.$store.state.webchat.current.webchat_todo.messageList[this.sessionId] || []
          if (currentHistory.length) {
            this.$nextTick(function () {
//            切换卡片时，加载聊天记录，完成之后，滚动条滚动到底部
              this.scrollToBottom({scrollName: 'chat_msg', warpName: 'msg_inner'})
              this.loadFlag = true
            })
            return
          }
        }
        // 获取客户信息
        let importSid = webchatUtils.getImportSidByPlantform(this.chatInfo.sid, this.chatInfo.platform)
        if (importSid) {
          let obj = {}
          if (this.$store.state.webchat.autoCust[this.sessionId]) {
            let autoCust = this.$store.state.webchat.autoCust[this.sessionId]
            if (autoCust) {
              obj = {
                autoCustName: autoCust.autoCustName || '',
                autoCustPhone: autoCust.autoCustPhone || '',
                autoCustObj: autoCust.autoCustObj || {},
                autoCustLength: autoCust.autoCustLength || 0,
                autoMatchContent: autoCust.autoMatchContent,
                autoMatchType: autoCust.autoMatchType
              }
            } else {
              obj = {
                autoCustName: '',
                autoCustPhone: '',
                autoCustObj: {},
                autoCustLength: 0,
                autoMatchContent: '',
                autoMatchType: ''
              }
            }
            this.$set(obj, 'importSid', importSid)
//            obj.importSid = importSid
            this.$store.commit(types.AUTO_CUST_INFO, {sessionId: this.sessionId, data: obj})
          }
        }
        // 查询当前会话聊天消息
        let queryData = {
          sessionId: this.sessionId,
          sid: this.chatInfo.sid,
          when: new Date().getTime(),
          limit: 10,
          whenStartTag: new Date().getTime(),  // 从最前面开始查找聊天记录
          currentSessionId: this.sessionId,
          submenu: this.tabType,
          isNew: true           // 用于标记是否为全部tab下的第一次请求，如果是的话，清掉之前的list数组
        }
        if (this.sessionId) { // 没有sessionId 不去请求历史消息
          this.$store.dispatch('queryMessageHistory', queryData).then(() => {
            console.log('boxNew queryNewMsgHistory')
            this.$nextTick(() => {
  //          第一次加载卡片，查询当前会话聊天记录之后，滚动条滚动到底部
              this.scrollToBottom({scrollName: 'chat_msg', warpName: 'msg_inner'})
              this.loadFlag = true
              let currentRoute = this.$route.path.split('/')
              if (currentRoute && currentRoute.indexOf('webchat_todo') > -1) {
                this.dealMsgFun()
              }
            })
          })
        }
      },
      changeImgEnter (src, event) {
        if (src) {
          event.target.setAttribute('data-gif', event.target.src)
          event.target.src = src
        }
      },
      changeImgLeave (src, event) {
        if (event.target.getAttribute('data-gif') && src) {
          event.target.src = event.target.getAttribute('data-gif')
        }
      },
      filterImag (src, index, status) { // 过滤图片 如果是gif 则转化为base64
        let self = this
        let imgItem = document.createElement('img')
        let w = 50
        let h = 50
        if (src) {
          if (this.AvatarList[src]) {
            return this.AvatarList[src]
          } else {
            imgItem.onload = function () {
              let c = document.createElement('canvas')
              let isC = !!(c.getContext && c.getContext('2d'))
              if (isC) {
                c.width = w
                c.height = h
                c.getContext('2d').drawImage(imgItem, 0, 0, w, h)
                var dataURL = c.toDataURL()
                self.AvatarList[src] = dataURL
                let item
                if (status === 'current' && document.querySelectorAll('.chatUserMsg .msg_li')[index]) {
                  item = document.querySelectorAll('.chatUserMsg .msg_li')[index].querySelector('.chat_item .chat_user_info_out img')
                } else if (status === 'history' && document.querySelectorAll('.chatHistoryMsg .msg_li')[index]) {
                  item = document.querySelectorAll('.chatHistoryMsg .msg_li')[index].querySelector('.chat_item .chat_user_info_out img')
                } else if (status === 'upload' && document.querySelectorAll('.chatUserMsg .uploaded')[index]) {
                  item = document.querySelectorAll('.chatUserMsg .uploaded')[index].querySelector('.chat_item .chat_user_info_out img')
                }
                if (item) {
                  item.src = dataURL
                }
              }
            }
            imgItem.crossOrigin = '*'
            imgItem.src = src
          }
        }
        return src
      },
      openWechatVideo (chatMsg) {
        this.$emit('videoReplay', {url: chatMsg.message, ChatMsg: chatMsg})
      },
      openGoodsInfoUrl (chatMsg) {
        if (chatMsg.cardInfo && chatMsg.cardInfo.url) {
          // 解决客户decode之后无法点击问题
          try{
            let url = decodeURIComponent(decodeURIComponent(chatMsg.cardInfo.url))
            window.open(url)
          } catch(error) {
            console.error(error)
          }
        }
        if ((chatMsg.newCardInfo && chatMsg.newCardInfo.target && chatMsg.contentType !== 'msgTask') || (chatMsg.contentType === 'msgTask' && chatMsg.newCardInfo && chatMsg.newCardInfo.target_url)) {
          try {
            let newCardInfoUrl = chatMsg.newCardInfo.target_url || chatMsg.newCardInfo.target
              let http = /^http:\/\/.*/i.test(newCardInfoUrl);
              let https = /^https:\/\/.*/i.test(newCardInfoUrl);
              if (!http && !https) {
                newCardInfoUrl = 'http://' + newCardInfoUrl;
              }
            window.open(newCardInfoUrl, '_blank')
          }
          catch {
            this.$message.error(this.$t('webchat.urlError'))
          }
        }
      },
      disabledFun (chatMsg) {
        let time = new Date()
        let timeNow = time.getTime() + this.nowTime
        if (!chatMsg.tipDisabled) {
          return
        } else if (chatMsg.when && timeNow - chatMsg.when > 120000) {
          chatMsg.tipDisabled = false
        }
      },
      NewMsgComming () {
        let lastnewMsg = this.messageList[this.messageList.length - 1]
        let containerHeight = 0
        let chatHeight = 0
        let scrollHeight = 0
        if (document.getElementsByClassName('chat_msg')[0]) {
          containerHeight = document.getElementsByClassName('chat_msg')[0].clientHeight
          scrollHeight = document.getElementsByClassName('chat_msg')[0].scrollTop
        }
        if (document.getElementsByClassName('msg_inner')[0]) {
          chatHeight = document.getElementsByClassName('msg_inner')[0].clientHeight
        }
        if (lastnewMsg && lastnewMsg.type === 'out') { // 发送消息过后留言提示消失
          this.leaveMsgIsClose = false
        }
        if (lastnewMsg && lastnewMsg.type === 'in' && lastnewMsg.msgType === 'newMsg' && !document.hidden && !lastnewMsg.dealCustomerMsg && this.tabType === 'webchat_todo') {
          let unReadMessageList = []
          this.messageList.map(item => {
            if (item.type === 'in' && !item.dealCustomerMsg) {
              unReadMessageList.push(item.messageId || item._id)
            }
          })
          let sendData = {
            sid: this.chatInfo.sid,
            accessId: this.chatInfo.accessId,
            sessionId: this.sessionId,
            messageIdList: unReadMessageList
          }
          this.$store.dispatch('dealImMsgFromUser', sendData)
        }
        if ((scrollHeight - (chatHeight - containerHeight)) < -67 && chatHeight > 0) {
          // 滚动状态中
          if (lastnewMsg && lastnewMsg.type === 'in' && lastnewMsg.msgType === 'newMsg') {
            if (lastnewMsg.contentType === 'text') {
              this.holdNewMsg.Msg = lastnewMsg.content
              this.holdNewMsg.Num++
              this.holdNewMsg.Show = true
              this.holdNewMsg.TimeOut && window.clearTimeout(this.holdNewMsg.TimeOut)
              if (this.holdNewMsg.Num === 1) {
                this.holdNewMsg.MsgId = lastnewMsg.messageId
              }
              let self = this
              this.holdNewMsg.TimeOut = window.setTimeout(() => {
                self.holdNewMsg.Show = false
              }, 3000)
              document.getElementsByClassName('chat_msg')[0].addEventListener('scroll', this.scrollEvent)
            } else if (lastnewMsg.contentType === 'file' || lastnewMsg.contentType === 'image' || lastnewMsg.contentType === 'voice' || lastnewMsg.contentType === 'link' || lastnewMsg.contentType === 'wechatvideo') {
              this.holdNewMsg.Num++
              if (this.holdNewMsg.Num === 1) {
                this.holdNewMsg.MsgId = lastnewMsg.messageId
              }
              document.getElementsByClassName('chat_msg')[0].addEventListener('scroll', this.scrollEvent)
            }
          }
        } else {
          if (document.getElementsByClassName('chat_msg').length > 0) {
            let that = this
            window.setTimeout(() => {
//              有新消息推送过来之后，滚动到底部
//              document.getElementsByClassName('chat_msg')[0].scrollTop = chatHeight
              that.scrollToBottom({scrollName: 'chat_msg', warpName: 'msg_inner'})
            }, 0)
          }
        }
      },
      scrollEvent () {
        let containerHeight = 0
        let chatHeight = 0
        let scrollHeight = 0
        if (document.getElementsByClassName('chat_msg')[0]) {
          containerHeight = document.getElementsByClassName('chat_msg')[0].clientHeight
          scrollHeight = document.getElementsByClassName('chat_msg')[0].scrollTop
        }
        if (document.getElementsByClassName('msg_inner')[0]) {
          chatHeight = document.getElementsByClassName('msg_inner')[0].clientHeight
        }
        if (scrollHeight - (chatHeight - containerHeight) > 50 && chatHeight > 0) {
          this.showHoldNewMsg()
        }
      },
      showHoldNewMsg (data) {
        this.holdNewMsg.Show = false
        this.holdNewMsg.Num = 0
        this.holdNewMsg.Msg = ''
        this.holdNewMsg.MsgId = ''
        this.holdNewMsg.TimeOut && window.clearTimeout(this.holdNewMsg.TimeOut)
        if (data === "unJump") {
          return
        }
        if (document.getElementsByClassName('msg_inner')[0] && document.getElementsByClassName('chat_msg').length > 0) {
//          点击未读消息条数，页面滚动到最底部
          this.scrollToBottom({scrollName: 'chat_msg', warpName: 'msg_inner'})
          document.getElementsByClassName('chat_msg')[0].removeEventListener('scroll', this.scrollEvent)
        }
      },
      showHoldNewMsgId () {
        if (this.holdNewMsg.MsgId) {
          let offsetTop = document.getElementsByClassName('msg_' + this.holdNewMsg.MsgId)[0].offsetTop
          this.$nextTick(function () {
            if (document.getElementsByClassName('chat_msg').length) {
              document.getElementsByClassName('chat_msg')[0].scrollTop = offsetTop - 30
            }
          })
        }
        this.showHoldNewMsg('unJump')
      },
      compareVersions (ver1, ver2) {
        try {
          const version1pre = parseInt(ver1.substr(1).replace(/\./g, ''), 10)
          const version2pre = parseInt(ver2.substr(1).replace(/\./g, ''), 10)
          return version1pre < version2pre ? false : true
        } catch (error) {
          return false
        }
      },
      msgClass (data) {
        var str = ''
        if (data.type === 'system' || data.type == 'imcsr') {
          str += ' system_li '
        }
        if (data.messageId) {
          // 新消息推送的时候，推过来的是messageId
          str += 'msg_' + data.messageId
        }
        return str
      },
      imageLoadClass (data) {
        var dataflag = true
        if (this.imageLoadErrorArr.length) {
          this.imageLoadErrorArr.forEach((item) => {
            if (item === data) {
              dataflag = false
            }
          })
        }
        if (dataflag) {
          return ''
        } else {
          return 'img_load_error'
        }
      },
      initData () {
        this.fetchData()
        let self = this
        if (this.webchatData && this.webchatData.sdkVersionCode) {
          this.sdkVcode = this.compareVersions(this.webchatData.sdkVersionCode, 'v3.3.0')
        }
        this.CSRShowToAgent = getCache('CSRShowToAgent') || 'all'
        this.$store.dispatch('getCache', {type: 'channelGlobalSet'}).then((channelGlobalSet) => {
          innerHtmlChannelColor(self)
          this.videoRecordStatus = channelGlobalSet.videorecord === '1'
          this.isShowDealMsgStatus = channelGlobalSet.isUserRead || false
        })
      }
    },
    watch: {
      'preloadedMsgCon': 'preloadedMsgConChange',
      sessionId () {
        if (this.$route.path.split('/')[2] === 'webchat') {
          this.showHoldNewMsg()
        }
      },
      messageListChange (newVal, oldVal) {
        if (oldVal !== undefined && newVal !== undefined && this.messageList.length > 0) {
          this.NewMsgComming()
        }
      },
      // imageUrls () {
      //   // imageUrls 更新时向上冒泡
      //   bus.$emit('updateImageUrls', this.imageUrls)
      // }
    },
    activated () {
//      切换模块之后，模块被重新激活，页面滚动到底部
      if (document.getElementsByClassName('msg_inner').length > 0 && document.getElementsByClassName('chat_msg').length > 0) {
        this.scrollToBottom({scrollName: 'chat_msg', warpName: 'msg_inner'})
      }
    },
    components: {
      WebchatChatVoice,
      webchatBigImage,
      orderInfoCard
    },
    computed: {
      // 聊天记录中的图片地址数组
      imageUrls () {
        let list = this.messageList
        let images = list.filter((item) => {
          let newStr = item.fileName ? item.fileName.substring(item.fileName.lastIndexOf('.')+1) : ''
          return item.contentType === 'image' || (item.contentType == 'file' && this.imgType.includes(newStr))
        })
        let urls = []
        images.forEach((item2) => {
          var pushflag = true
          if (this.imageLoadErrorArr.length) {
            this.imageLoadErrorArr.forEach((errLi) => {
              if (item2._id === errLi) {
                pushflag = false
              }
            })
          }
          if (pushflag) {
            urls.push(common.urlDeal(item2.message))
          }
        })
        let nowIndex = urls.findIndex(photo => photo === this.currentImgUrl)
        if (nowIndex > -1) {
          let start = urls.slice(0, nowIndex)
          let end = urls.slice(nowIndex)
          urls = [...end, ...start]
        }
        return urls
      },
      chatMsgClass () {
        console.log(this.initiativeSession)
        let inputHeight = this.$store.state.webchat.webchatList.inputHeight === 'gaodusuoxiao' ? 'chat_msg_laogao' : 'chat_msg_suoxiao'
        let str = this.initiativeSession ? 'initiative' : ''
        let data = this.chatMsgCon.font + ' ' + str + ' ' + inputHeight
        console.log(data)
        return data
      },
      messageList: {
        // getter
        get: function () {
          let messageList = []
          if (this.$store.state.webchat.current[this.tabType] && this.$store.state.webchat.current[this.tabType].messageList[this.sessionId]) {
            messageList = deepClone(this.$store.state.webchat.current[this.tabType].messageList[this.sessionId])
          } else if(this.message){// 工单关联会话
            messageList = deepClone(this.message)
          } else {
            return []
          }
          let ishistory = true
          messageList.forEach((obj, index) => {
            if (obj.message.indexOf('&lt;7moorbr/&gt;') > -1 || obj.message.indexOf('<7moorbr/>') > -1) {
              obj.message = obj.message.replace(/<7moorbr\/>/g, '<br />')
              obj.message = obj.message.replace(/&lt;7moorbr\/&gt;/g, '<br />')
            }
//            会话消息，回显的时候，回车没有替换成br处理
            obj.message = obj.message.replace(/[\n\r]/g, '<br />')
            obj = this.filterImIcon(obj, ishistory)
            obj.message = filterXSS(obj.message)
            if (obj.contentType === 'cardInfo') {
              if (this.showExtraInfoMap[obj._id] === undefined) {
                this.$set(this.showExtraInfoMap, obj._id, false)
              }
            }
            if ((obj.contentType === 'newCardInfo' || obj.contentType === 'msgTask' || obj.msgType === 'msgTask') && obj.newCardInfo && obj.newCardInfo !== 'undefined') {
              try {
                obj.newCardInfo = JSON.parse(obj.newCardInfo)
              }
              catch {
                try {
                  obj.newCardInfo = JSON.parse(decodeURIComponent(obj.newCardInfo))
                }
                catch {
                  obj.newCardInfo = JSON.parse(obj.newCardInfo)
                }
              }
              if (obj.newCardInfo.tags && obj.newCardInfo.tags.length > 0) {
                obj.newCardInfo.tags = obj.newCardInfo.tags.slice(0, 2)
              }
            }
            if (obj.dealUserMsg === true) {
              obj.dealMsgStatus = this.$t('webchat.dealMsgRead')
            } else if (obj.dealUserMsg === false) {
              obj.dealMsgStatus = this.$t('webchat.dealMsgUnRead')
            }
            // 表单消息被删除时，发送表单消息，不应展示消息发送状态
            if (obj.sendStatus === 'fail' && obj.contentType === 'sessionForm') {
              obj.dealMsgStatus = ''
            }
            if (obj.contentType === 'sessionForm') {
              try {
                obj.sessionForm = JSON.parse(obj.sessionForm)
              }
              catch {}
            }
            if (obj.contentType === 'sessionFormSubmit') {
              try {
                obj.sessionFormSubmit = JSON.parse(obj.sessionFormSubmit)
              }
              catch {}
            }
            if (obj.contentType === 'xbotFormSubmit') {
              try {
                obj.xbotFormSubmit = JSON.parse(obj.xbotFormSubmit)
              }
              catch {}
            }
            if (obj.contentType === 'xbotForm') {
              try {
                obj.xbotForm = JSON.parse(obj.xbotForm)
              }
              catch {}
            }
            if (obj.clientAutoClose) {
              // 访客端会话被自动结束
              obj.message = this.$t('webchat.clientAutoClose')
            }
          })
          return messageList
        }
      },
      messageListChange () {
        if (this.tabType === 'webchat_todo') {
          return this.$store.state.webchat.current.webchat_todo.messageListChange[this.sessionId]
        }
      },
      preloadedMsgCon () {
        // 预加载的消息
        if (this.tabType === 'webchat_todo' && this.$store.state.webchat.preload[this.sessionId]) {
          return this.$store.state.webchat.preload[this.sessionId].preloadedMsgCon || ''
        } else {
          return ''
        }
      },
      preloadedFlag () {
        if (this.tabType === 'webchat_todo' && this.$store.state.webchat.preload[this.sessionId]) {
          return this.$store.state.webchat.preload[this.sessionId].preloadedFlag || ''
        } else {
          return ''
        }
      },
      tabType () {
        let arr = this.$route.path.split('/')
        return arr[3]
      },
      sessionId () {
        let sessionId = ''
        if (this.$route.path.split('/')[2] === 'webchat') {
          sessionId = this.$route.path.split('/')[4]
        }
        return sessionId
      },
      webchatData () {
        //  会话的详细信息
        if (this.tabType === 'webchat_todo' && this.$store.state.webchat.current.webchat_todo.currentSession[this.sessionId]) {
          return this.$store.state.webchat.current.webchat_todo.currentSession[this.sessionId]
        } else if (this.tabType === 'webchat_all' && this.$store.state.webchat.current.webchat_all.currentSession) {
          return deepClone(this.$store.state.webchat.current.webchat_all.currentSession)
        } else if (this.tabType === 'webchat_robot' && this.$store.state.webchat.current.webchat_robot.currentSession) {
          return deepClone(this.$store.state.webchat.current.webchat_robot.currentSession)
        } else if (this.tabType === 'webchat_laterProcess' && this.$store.state.webchat.current.webchat_laterProcess.currentSession) {
          return deepClone(this.$store.state.webchat.current.webchat_laterProcess.currentSession)
        } else if (this.tabType === 'webchat_queue' && this.$store.state.webchat.current.webchat_queue.currentSession) {
          return deepClone(this.$store.state.webchat.current.webchat_queue.currentSession)
        } else {
          return {}
        }
      },
      // 留言会话
      isLeaveMsg () {
        return this.tabType === 'webchat_todo'
               && this.webchatData.leavemsg
               && (this.chatInfo.platform === 'pc' || this.chatInfo.platform === 'wap')
               && this.leaveMsgIsClose
      },
      // 主动会话
      isActiveSession () {
        return (this.tabType === 'webchat_laterProcess' || this.tabType === 'webchat_all' || this.tabType === 'webchat_robot')
          && this.chatInfo.status === 'finish'
          && (this.chatInfo.platform === 'pc' || this.chatInfo.platform === 'wap')
          && this.activeSessionIsclose
      },
      nowTime () {
        return this.$store.state.webchat.nowTimeDiff || 0
      },
      chatInfo () {
        let messageObj
        if (this.tabType === 'webchat_todo' && this.$store.state.webchat.current.webchat_todo.chatInfoById[this.sessionId]) {
          messageObj = deepClone(this.$store.state.webchat.current.webchat_todo.chatInfoById[this.sessionId])
        } else if (this.tabType === 'webchat_all' && this.$store.state.webchat.current.webchat_all.chatInfoById) {
          messageObj = deepClone(this.$store.state.webchat.current.webchat_all.chatInfoById)
        } else if (this.tabType === 'webchat_robot' && this.$store.state.webchat.current.webchat_robot.chatInfoById) {
          messageObj = deepClone(this.$store.state.webchat.current.webchat_robot.chatInfoById)
        } else if (this.tabType === 'webchat_laterProcess' && this.$store.state.webchat.current.webchat_laterProcess.chatInfoById) {
          messageObj = deepClone(this.$store.state.webchat.current.webchat_laterProcess.chatInfoById)
        } else if (this.tabType === 'webchat_queue' && this.$store.state.webchat.current.webchat_queue.chatInfoById) {
          messageObj = deepClone(this.$store.state.webchat.current.webchat_queue.chatInfoById)
        } else {
          return {}
        }
        messageObj = this.filterImIcon(messageObj)
        return messageObj
      },
      chat_msg_ai_height () {
        let webchatList = this.$store.state.webchat.webchatList.webchat_todo.list
        let answers = []
        if (webchatList.length > 0) {
          webchatList.forEach((item) => {
            if (item._id === this.sessionId) {
              if (item.m7RobotAnswers && item.m7RobotAnswers.length > 0) {
                answers = item.m7RobotAnswers
              }
            }
          })
        }
        if (this.isLeaveMsg) {
          return {
            height: 'calc( 100vh - 315px)'
          }
        }
        if (this.isActiveSession && !this.isEcommerce) {
          return {
            height: 'calc( 100vh - 227px)'
          }
        }
        if (this.tabType === 'webchat_queue') {
          return {
            height: 'calc( 100vh - 157px)'
          }
        }
        if (answers.length === 0) {
          return {}
        } else if (answers.length === 1) {
          return {
            height: 'calc( 100vh - 280px)'
          }
        } else if (answers.length === 2) {
          return {
            height: 'calc( 100vh - 303px)'
          }
        } else {
          return {}
        }
      },
      satisfactioEvaluation () {
        return this.$store.state.session.user.funcIds && contains(this.$store.state.session.user.funcIds, 'func_satisfactio_evaluation')
      },
//      控制消息发送状态是否展示
      userId () {
        return this.$store.state.session.user._id
      }
    },
    mounted () {
      // 切换tab再切回来时，需要重新emit iamgeUrls
      // bus.$emit('updateImageUrls', this.imageUrls)
      bus.$on('renderWebchatContainer', (msg) => {
        this.showHoldNewMsg()
        this.initData()
        if (!this.isEcommerce) {
          window.addEventListener('focus', this.handleWinFocus) // 监听窗口聚焦
        }
        console.log('==========renderWebchatContainer-WebchatConMsgBox==========')
      })
      bus.$on('serHeaderImg', ({headUrl}) => {
        this.$store.commit(typesOn.SET_IMAGES,{id:this.sessionId,headUrl})
      })
      // 触发上传事件 
      bus.$on('toReSend', (file) => {
        this.reSendFile = file
      })
    },
    beforeDestroy () {
      bus.$off('renderWebchatContainer')
      bus.$off('serHeaderImg')
      bus.$off('toReSend')
      window.removeEventListener('focus', this.handleWinFocus) // 销毁窗口聚焦      
      console.log('==========beforeDestory-WebchatConMsgBox==========')
    }
  }
</script>
<style lang="stylus" scoped>
  @import "./style/webchatCon.styl"
  .leaveMsgNotice
    padding 15px
    height 72px
    background-color #FDF6EC
    color #E6A23C
    font-size 12px
    line-height 42px
    width: 100%;
    box-sizing: border-box;
    p
     position relative
    .leveaClose
      top -7px
      right -2px
      position absolute
      color #ccc
      margin-right 5px
      font-size 16px
    .leveaClose:hover
      cursor pointer
  .send_status.failure
    color $c-pink
    text-align center
    line-height 20px
    font-size 20px
    position absolute
    left -0.5em
    top 50%
    transform translateY(-50%)
    padding 13px
  .chat_send_status
    display inline-block
    background url(./img/webchat_send.gif) no-repeat
    background-size 20px 20px
    position absolute
    left 4px
    top 6px
    width 20px
    height 20px
  .chat_send_status_in
    display inline-block
    background url(./img/webchat_send.gif) no-repeat
    background-size 20px 20px
    position relative
    left 12px
    top 6px
    width 20px
    height 20px
  .chat_send_status.success, .chat_send_status_in.success
    display none
  .chat_send_status.fail, .chat_send_status_in.fail
    display inline-block
    background url(./img/reply_error.png) no-repeat
    background-size 20px 20px
  .weixinHead
    height 32px
    width 32px
    position relative
    border-radius: 50%
    box-sizing: border-box
    text-align: center
    display: inline-block
    line-height 32px
  .defaultHead
    background-color #3cc1f7
    color #fff
    .icon-fangkeduanyonghutouxiang
      font-size 20px
  .robot_default
    background-color #BFBFBF
    color: #fff
  .chat_msg_miniprog_info
    width 100%
    max-width 175px
    overflow hidden
    padding 10px
    background #fff
    margin-bottom 10px
    border solid 1px #d9d9d9
    border-radius 4px
    cursor pointer
    margin-left 5px
    .miniprogInfo
      border-bottom 1px solid #d9d9d9
      margin-bottom 10px
    .miniprogImg
      height 150px
      width 150px
      text-align center
      display inline-block
      margin 10px 10px
    .miniprogTitle
      width 100%
    .miniprogImg img
      max-height 150px
      max-width 150px
    .im_wxminiIcon:before
      content "\e716"
    .im_wxminiIcon
      margin-right 5px
      font-family "iconfont" !important
      font-style: normal
      -webkit-font-smoothing antialiased
      color #459ae9 !important
  .chat_msg_newCardInfo
    cursor pointer
    width: 300px
    min-height: 100px
    padding 10px
    position relative
    border-radius 14px
    background #ffffff
    display inline-block
    line-height 26px
    background #ffffff
    margin: 0 10px
    border 1px solid #EBEBEB
    clear both
    .chat_cardInfo_arrow_out
      border-left 6px solid #EBEBEB
      border-top 6px solid transparent
      border-bottom 6px solid transparent
      border-right 6px solid #EBEBEB
      content ' '
      position absolute
      width 0
      height 0
      right -9px
      top 6px
      border-radius 1px
      transform rotate(83deg)
      border 5px solid #EBEBEB
      border-color transparent transparent #EBEBEB #EBEBEB
    .chat_cardInfo_arrow_out::after
      content: ' ';
      position: absolute;
      width: 0;
      height: 0;
      right: -4px;
      top: -3px;
      border-radius: 1px;
      -webkit-transform: rotate(83deg);
      transform: rotate(0);
      border: 4px solid #fff;
      border-color: transparent transparent #fff #fff;
      border-color transparent transparent #fff #fff
    .chat_cardInfo_arrow
      border-top 6px solid transparent
      border-bottom 6px solid transparent
      border-right 6px solid #EBEBEB
      content ' '
      position absolute
      width 0
      height 0
      left -9px
      top 15px
      border-radius 1px
      transform rotate(95deg)
      border 5px solid #EBEBEB
      border-color #EBEBEB transparent transparent #EBEBEB
    .chat_cardInfo_arrow::after
      content: ' ';
      position: absolute;
      width: 0;
      height: 0;
      right: -4px;
      top: -5px;
      border-radius: 1px;
      -webkit-transform: rotate(83deg);
      transform: rotate(0);
      border: 4px solid #fff;
      border-color: #fff transparent transparent #fff;
  .chat_msg_newCardInfo_top
    overflow hidden
    clear both
    height 80px
    img
      float left
      width 80px
      height 100%
      border-radius 3px
    .newCardInfo_top_right
      float right
      width 210px
      padding-top 4px
      .newCardInfoSecond
        overflow hidden
        clear both
        margin-top 2px
        line-height 17px
      .newCardInfoTitle
        color #000000
        font-size 12px
        font-weight 400  
        overflow: hidden;
        -webkit-line-clamp: 2;
        display: -webkit-box;
        /*! autoprefixer: off */
        -webkit-box-orient: vertical;
        /*! autoprefixer: on */
        text-overflow: ellipsis;
        line-height 17px
      .newCardInfoSubTitle
        color: #595959
        white-space nowrap
        overflow hidden
        text-overflow ellipsis
      .newCardInfoSubTitleTwo
        color #878787
        display -webkit-box
        -webkit-line-clamp 1
        -webkit-box-orient vertical
        overflow hidden
        text-overflow ellipsis
      .newCardInfoAttrOne
        float right
        max-width 48px
        overflow hidden
        white-space nowrap
        text-overflow ellipsis
      .newCardInfoPrice
        color #FF6B6B
        font-weight 800
        font-size 14px
        line-height 17px
        overflow hidden
        white-space nowrap
        text-overflow ellipsis
        max-width 100px
        float left
      .newCardInfoAttrTwo
        overflow hidden
        white-space nowrap
        text-overflow ellipsis
        max-width 100px
        line-height 17px
        float right
  .newCardInfoDecs
    margin-top 10px
    p
      padding 2px 0px
      overflow hidden
      white-space nowrap
      text-overflow ellipsis
      color #595959
  .newCardInfoBtn
    clear both
    overflow hidden
    float right
    text-align right
    li
      display inline-block
      padding 5px
      margin-left 5px
  .robot_cardinfo.chat_msg_newCardInfo
    min-height unset
  .robot_cardinfo
    .newCardInfoTitle
      line-height 20px
      p
        display inline-block
      .robotCardInfoCon
        max-width calc(100% - 60px)
        text-overflow ellipsis
        overflow hidden
      .newCardInfoPrice
        float right
        max-width 60px
    .robotCardInfoThird
      line-height 20px
      p
        display inline-block
  .ecommerceCardInfo
    background-color #ffffff
    padding 10px
    clear both
    overflow hidden
    .ecommerceCardInfoImg
      width 56px
      height 56px
      float left
    .ecommerceCardInfoRight
      float left
      margin-left 10px
      .ecommerceCardInfoTitle
        width 208px
        float left
        color #262626
        margin-bottom 6px
        overflow hidden
        text-overflow ellipsis
        display -webkit-box
        -webkit-line-clamp 2
        -webkit-box-orient vertical      
      .ecommercePrice
        color #FF5C5C
        font-size 14px    
  .voiceToText
    cursor pointer
  .voiceToTextBox
    background-color #f0f0f0
    border-radius 6px
    padding 10px
    margin 10px
    max-width 250px
    display inline-block
  .voiceToTextSending
    background url(./img/voiceTotextLoad.gif) no-repeat
    background-size 20px 20px
    width 30px
    height 20px
  .voiceToTextIcon
    display none
    width 30px
    color #A6A6A6
  .voiceToTextIcon:hover
    color #459AE9
  .voiceToTextIn
    margin-left 10px
    text-align right
  .voiceToTextOut
    margin-right 10px
    text-align left
  .voiceMessage:hover .voiceToTextIcon
    display inline-block
    font-size 14px
  .play_icon
    position absolute
    width 64px
    height 64px
    margin -32px 0 0 -32px
    top 50%
    left 50%
    background url('./img/play_icon.png') no-repeat center 0
    z-index 2
  .chat_dealMsg_status
    width 40px
    height 20px
    position absolute
    left 0px
    bottom 0px  
  .sessionForm
    min-height 40px
    margin-top 10px
  .checkSessionForm
    font-size 12px
    padding 0
  .formMsgLi
    width 100%
    line-height 20px
    span
      word-break break-word
  .resend
    display inline-block
    margin 20px 5px 0 0
    color $c-pink
    font-size 16px
    cursor pointer
  .chat_content
    .chat_img.img_load_error
      max-width none
  .withdrawReedit
    font-size 12px
</style>
<style lang="stylus">
  .chat_img
    .el-icon-circle-close
      color #ffffff
</style>
